
import { Toast } from 'vant'
import axios from 'axios'
import store from '@/store'
const request = axios.create({
  baseURL: 'http://toutiao.itheima.net/'
})
let cancelArr = []

request.interceptors.request.use(
  config => {
    if (!config.noToken) {
      config.headers.Authorization = 'Bearer ' + store.state.tokenObj.token
    }
    cancelArr = cancelArr.filter(item => {
      if (item.url === config.url && item.method === config.method) {
        item.fn()
        return false
      }
      return true
    })
    if (!config.noCancel) {
      config.cancelToken = new axios.CancelToken(cancelFn => {
        cancelArr.push({
          url: config.url,
          method: config.method,
          fn: cancelFn
        })
      })
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
request.interceptors.response.use(
  res => {
    return res
  },
  async error => {
    console.log('响应拦截error', error)
    if (error.response && error.response.data) {
      if (error.response.status === 401) {
        try {
          const res = await axios({
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            method: 'put',
            headers: {
              Authorization: 'Bearer ' + store.state.tokenObj.refresh_token
            }
          })
          console.log('成功', res)
          store.commit('setTokenObj', {
            token: res.data.data.token,
            refresh_token: store.state.tokenObj.refresh_token
          })
          return request(error.config)
        } catch (error) {
          Toast.fail(error.response.data.message)
          store.commit('logout')
        }
      } else {
        Toast.fail(error.response.data.message)
      }
    }
    return Promise.reject(error)
  }
)
export default request
